import { timeout as baseTimeout, baseUrl } from "@/config/request.js"
export const objToParams = (obj) => {
    let params = ''
    for (let key in obj) {
        params += `${key}=${obj[key]}&`
    }
    return `?${params.slice(0, -1)}`
}
const ajax = ({ url, data, params, method = 'GET', timeout = baseTimeout, progress }) => {
    method = method.toUpperCase()
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        if (method === 'GET') {
            url += objToParams(params)
        }
        xhr.open(method, `${baseUrl}${url}`)
        xhr.timeout = timeout
        xhr.ontimeout = function (event) {
            console.log('ajax timeout:', event, this);
        }
        if (progress) {
            xhr.addEventListener('progress', (event) => progress(event, xhr))
        }
        xhr.onreadystatechange = (event) => {
            // 0: 请求未初始化
            // 1: 服务器连接已建立
            // 2: 请求已接收
            // 3: 请求处理中
            // 4: 请求已完成，且响应已就绪
            if (event.target.readyState === 4) {
                if (event.target.status === 200) {
                    const result = typeof event.target.responseText === 'object' ? JSON.parse(event.target.responseText) : event.target.responseText
                    console.log('sdfds', result, event.target);
                    return resolve(result)
                }
                return reject(event.target)
            }
        }
        if (method === 'POST') {
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.send(JSON.stringify(data))
        } else {
            xhr.send(null)
        }
    })
}
export default ajax